package org.example.hospital_frontend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.hospital_frontend.common.Result;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.domain.UserUpdateRequest;
import org.example.hospital_frontend.service.UserService;
import org.example.hospital_frontend.service.UserUpdateRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/updateRequest")
public class AdminUpdateRequestController {

    @Autowired
    private UserUpdateRequestService updateRequestService;
    @Autowired
    private UserService userService;

    // 查询所有待审核申请
    @GetMapping("/list")
    public Result<List<UserUpdateRequest>> list() {
        QueryWrapper<UserUpdateRequest> qw = new QueryWrapper<>();
        qw.eq("status", 0);
        return Result.success(updateRequestService.list(qw));
    }

    // 审核（通过/拒绝）
    @PostMapping("/review")
    public Result review(@RequestBody Map<String, Object> req, HttpServletRequest request) {
        Integer id = (Integer) req.get("id");
        Integer status = (Integer) req.get("status"); // 1通过 2拒绝
        if (id == null || status == null) return Result.error("参数错误");
        UserUpdateRequest updateRequest = updateRequestService.getById(id);
        if (updateRequest == null || updateRequest.getStatus() != 0) return Result.error("申请不存在或已处理");

        // 审核通过则更新user表
        if (status == 1) {
            User user = userService.getById(updateRequest.getUserId());
            if ("history".equals(updateRequest.getFieldName())) {
                user.setHistory(updateRequest.getNewValue());
            } else if ("allergy".equals(updateRequest.getFieldName())) {
                user.setAllergy(updateRequest.getNewValue());
            }
            userService.updateById(user);
        }
        updateRequest.setStatus(status);
        updateRequest.setReviewTime(new Date());
        // 可记录reviewerId
        updateRequestService.updateById(updateRequest);
        return Result.success();
    }
}